<?php

namespace App\Utility;

use EasySwoole\Component\Context\ContextManager;

class Response
{


    static public function returnJson($code , $msg =""  ,$data =[]){
        if(!is_string($msg) ){
            $data = $msg;
            $msg  = "" ;
        }
        $data = json_encode([
            'code'=>$code,
            'msg'=> $msg?:\App\Consts\ErrorCode::ERROR_CODE_AND_ERORR_MSG[$code],
            'data'=> (object)$data
        ]);
        return $data;
    }

    static public function responseString($string){
        $response = ContextManager::getInstance()->get('response');
        $response->withHeader('Content-type','application/json;charset=utf-8');
        $response->withStatus(200);
        $response->write($string);
        $response->end();
    }

    static public function responseJson($code , $msg =""  ,$data = []){

        try {

            if(!is_string($msg)){
                $data = $msg;
                $msg  = "" ;
            }
            $datas = $data;
            $request = ContextManager::getInstance()->get('request');
            $response = ContextManager::getInstance()->get('response');
            if($response){
                if(!isset($request->getHeaders()['user-agent'])){
                    var_dump("user-agent error ,code:".$code);
                    $data = json_encode([
                        'code'=>$code,
                        'msg'=> "弟弟别迷路！",
                        'data'=> $datas
                    ]);

                    $response->withHeader('Content-type','application/json;charset=utf-8');
                    $response->withStatus(200);
                    $response->write($data);
                    $response->end();
                    return ;

                }

                if(in_array("android",$request->getHeaders()['user-agent']) ){
                    if (empty($data) && $data !== 0) {
                        $datas = new \stdClass();
                    } else {
                        $datas = new \stdClass();
                        $datas->info = $data;
                    }
                }

                $data = json_encode([
                    'code'=>$code,
                    'msg'=> $msg?:\App\Consts\ErrorCode::ERROR_CODE_AND_ERORR_MSG[$code],
                    'data'=> $datas
                ]);

                $response->withHeader('Content-type','application/json;charset=utf-8');
                $response->withStatus(200);
                $response->write($data);
                $response->end();
            }


        }catch (\Throwable $e){

            var_dump($e->getMessage());
            var_dump($e->getTraceAsString());
        }


    }





}